<?php
/**
 * Class SystemAction
 * 活动相关的控制器
 */
Class PartyAction extends Action {

    public function index(){
        $this->show('You Can not access this page in this way.');
    }

    public function merry(){
        $val = I('id');
        session('val',$val);
        $this->display();//输出页面模板
    }
    /**
     * 获取离当前时间最近的一条记录
     */
    public function viewById(){
        $val = session("val");
        $partyModel = D('Party');
        $parties = $partyModel
            ->relation(true)
            //->where('TIMESTAMPDIFF(MINUTE,begin,now())<0')
//            ->order('ABS(TIMESTAMPDIFF(MINUTE,begin,now())) asc')
            ->find($val);
        $this->ajaxReturn($parties);
    }
    /**
     * 获取活动类表 AJAX
     */
    public function getParty(){
        $page = I('page');
        $limit = I('limit');
        if($page==null || $limit==null){
            $p = M('Party');
            $this->ajaxReturn($p->count());
        }else{
            $from = ($page-1)*$limit;
            $to = $from+$limit;
            $partyModel = D('Party');
            $parties = $partyModel
                ->relation(true)
                ->order('ABS(TIMESTAMPDIFF(MINUTE,begin,now())) asc')
                ->limit($from,$to)
                ->select();
            $this->ajaxReturn($parties);
        }
    }

    /**
     * 获取离当前时间最近的一条记录
     */
    public function latest(){
        $partyModel = D('Party');
        $parties = $partyModel
            ->relation(true)
            //->where('TIMESTAMPDIFF(MINUTE,begin,now())<0')
            ->order('ABS(TIMESTAMPDIFF(MINUTE,begin,now())) asc')
            ->find();
        $this->ajaxReturn($parties);
    }

    public function test(){
        $root = $_SERVER["CONTEXT_DOCUMENT_ROOT"];
        var_dump($root);
        exit();
    }

    /**
     * 上传图片 Ajax
     */
    public function saveParty(){
        if(session('user') == null){ $this->show('没有执行此操作权限');exit();}

        $man = I('rightManName');
        $woman = I('rightWomanName');
        $begin = I('beginTime');
        $end = I('endTime');

        if($man==null || $man==''){$this->show('新郎名称不能为空');exit(); }
        if($woman==null || $woman==''){$this->show('新娘名称不能为空');exit(); }
        if($begin==null || $begin==''){$this->show('活动开始时间不能为空');exit(); }
        if($end==null || $end==''){$this->show('活动结束时间不能为空');exit(); }


        $data['man'] = $man;
        $data['woman'] = $woman;
        $data['begin'] =  date("Y-m-d H:i:s",strtotime($begin));
        $data['end'] =  date("Y-m-d H:i:s",strtotime($end));

        $partyModel = M('party');
        $party_id = $partyModel->add($data);
        if(!$party_id){
            $this->show('活动保存失败');
            exit();
        }else{
            $images = array();
            $todayDateStr = date('Ymd',time());
            $uploadPath = '.'.DIRECTORY_SEPARATOR.
                          'Public'.DIRECTORY_SEPARATOR.
                          'upload'.DIRECTORY_SEPARATOR.
                          $todayDateStr.DIRECTORY_SEPARATOR;
            if(!file_exists($uploadPath)){
                if(!mkdir($uploadPath,0777,true)){
                    $this->show('无法创建文件目录');
                    exit();
                }
            }
            import('ORG.Net.UploadFile');
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 81457280 ;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath =  $uploadPath;// 设置附件上传目录
            $upload->thumb = true;
            if(!$upload->upload()) {// 上传错误提示错误信息
                $this->show($upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $info =  $upload->getUploadFileInfo();
                foreach($info as $img){
                    array_push($images, array(
                            'name'=>$todayDateStr.DIRECTORY_SEPARATOR.$img['savename'],
                        'party_id'=>$party_id
                    ));
//                    $imageModel = M('image');
//                    $imageModel ->add($images);
                }
                $imageModel = M('image');
                $imageModel->addAll($images);
                $this->show('null');
            }
        }
    }
    //删除活动
    public function deleteParty(){
        if(session('user') == null){$this->show('没有执行此操作权限');exit();}

        $id = I('id');
        if($id == null || $id == ''){ $this->show('没有指定要删除的活动ID'); exit(); }

        $pd = D('Party');
        $rs = $pd->relation(true)->where(array('id'=>$id))->select();
        $imgs = $rs[0]['images'];
        if($imgs!=null && sizeof($imgs)>0){
            $firstImg = $imgs[0]['name'];
            $dirFileArr = preg_split('/\/|\\\/',$firstImg);
            //$root = $_SERVER["CONTEXT_DOCUMENT_ROOT"];
            $dirName = '.'.DIRECTORY_SEPARATOR.
                    'Public'.DIRECTORY_SEPARATOR.
                    'upload'.DIRECTORY_SEPARATOR.$dirFileArr[0];
            foreach($imgs as $img){
                $name = $img['name'];
                $fileName = '.'.DIRECTORY_SEPARATOR.
                    'Public'.DIRECTORY_SEPARATOR.
                    'upload'.DIRECTORY_SEPARATOR.$name;
                if(file_exists($fileName)){
                    unlink($fileName);
                }
            }

            if($this->is_empty_dir($dirName)){
                rmdir($dirName);
            }
        }

        //先删除图片
        $count = M('image')->where(array('party_id'=>$id))->count();
        if($count >0){
            $rsImg = M('image')->where(array('party_id'=>$id))->delete();
            if(!$rsImg){
                $this->show('图片数据失败:'+$rs);
                exit();
            }
        }
        //再删除活动
        $rs = $pd->where(array('id'=>$id))->delete();
        if(!$rs ){
            $this->show('活动数据失败:'.$rs);
            exit();
        }
        $this->show('null');
    }

    private function is_empty_dir($fp)
    {
        $H = @opendir($fp);
        $i=0;
        while($_file=readdir($H)){
            $i++;
        }
        closedir($H);
        if($i>2){
            return false;
        }else{
            return true;  //true
        }
    }
}